<!--
 * @Description: 
 * @Version: 2.0
 * @Date: 2021-08-09 10:19:51
 * @LastEditors: huangyue
 * @LastEditTime: 2021-09-06 17:56:54
-->
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>图片懒加载</title>
    <style>
      img {
        display: block;
        width: 100%;
        height: 300px;
        margin-bottom: 20px;
      }
      #container {
        height: 800px;
        overflow: scroll;
      }
    </style>
  </head>
  <body>
    <div id="container">
      <img data-src="./images/1.jpg" alt="" />
      <img data-src="./images/2.jpg" alt="" />
      <img data-src="./images/3.jpg" alt="" />
      <img data-src="./images/4.jpg" alt="" />
      <img data-src="./images/5.jpg" alt="" />
      <img data-src="./images/6.jpg" alt="" />
      <img data-src="./images/7.jpg" alt="" />
      <img data-src="./images/8.jpg" alt="" />
      <img data-src="./images/9.jpg" alt="" />
      <img data-src="./images/10.jpg" alt="" />
    </div>
  </body>
  <script>
    let imgArry = document.getElementsByTagName("img");
    let container = document.getElementById("container");
    let n = 0; //图片加载的数量

    //事件监听
    container.addEventListener("scroll", () => {
      lazyLoad(imgArry);
    });
    function lazyLoad(imgArry) {
      let clientHeight = container.clientHeight;
      let scrollTop = container.scrollTop;
      if (n > imgArry.length) return;
      for (let i = n; i < imgArry.length; i++) {
        if (imgArry[i].offsetTop < clientHeight + scrollTop) {
          imgArry[i].src = imgArry[i].getAttribute("data-src");
        }
      }
    }
    window.onload = lazyLoad(imgArry);
  </script>
</html>
